﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;

namespace Light_Notes
{
    [Flags]
    public enum FindOptions
    {
        None = 0,
        MatchCase = 1,
        MatchWholeWord = 2,
    }

    public class FindHelper
    {
        public static TextRange FindText(TextPointer position, string text, FindOptions findOptions, LogicalDirection direction)
        {
            TextRange textRange = null;

            StringComparison stringComparison;
            if ((findOptions & FindOptions.MatchCase) != 0)
                stringComparison = StringComparison.Ordinal;
            else
                stringComparison = StringComparison.OrdinalIgnoreCase;

            while (position != null)
            {
                if (position.GetPointerContext(direction) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(direction);

                    int indexInRun;
                    if (direction == LogicalDirection.Forward)
                        indexInRun = textRun.IndexOf(text, stringComparison);
                    else
                        indexInRun = textRun.LastIndexOf(text, stringComparison);

                    if (indexInRun >= 0)
                    {
                        TextPointer tp;
                        if (direction == LogicalDirection.Forward)
                            tp = position.GetPositionAtOffset(indexInRun);
                        else
                            tp = position.GetPositionAtOffset(indexInRun - textRun.Length);
                        textRange = new TextRange(tp, tp.GetPositionAtOffset(text.Length));

                        if ((findOptions & FindOptions.MatchWholeWord) == 0 ||
                            IsWholeWord(textRange)) break;
                        else textRange = null;
                    }

                    if (direction == LogicalDirection.Forward)
                        position = position.GetPositionAtOffset(textRun.Length);
                    else
                        position = position.GetPositionAtOffset(-textRun.Length);
                }
                else
                    position = position.GetNextContextPosition(direction);
            }

            return textRange;
        }

        private static bool IsWholeWord(TextRange textRange)
        {
            char[] ch = new char[1];

            textRange.Start.GetTextInRun(LogicalDirection.Backward, ch, 0, 1);
            if (!char.IsLetterOrDigit(ch[0]))
            {
                textRange.End.GetTextInRun(LogicalDirection.Forward, ch, 0, 1);
                return !char.IsLetterOrDigit(ch[0]);
            }

            return false;
        }
    }
}
